package common;

import java.io.*;

public class GenericSerializationUtil<T extends Serializable> {

    /**
     * 序列化任意实现了Serializable接口的对象到文件。
     *
     * @param obj    要序列化的对象
     * @param filename 文件的路径和名称
     */
    public static <T extends Serializable> void serializeObject(T obj, String filename) {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename))) {
            out.writeObject(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文件反序列化对象
     *
     * @param filename 文件名
     * @return 反序列化的对象
     */
    public static <T extends Serializable> T deserializeObject(String filename, Class<T> type) {
        T obj = null;
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename))) {
            obj = type.cast(in.readObject());
        } catch (IOException | ClassCastException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return obj;
    }
}